/**
 * 
 */
package durak.server.control;

import java.util.ArrayList;
import java.util.List;

import durak.server.model.GamingTable;
import durak.server.model.Player;

/**
 * Game class is responsible for the process of adding new human players to the
 * game holds a reference to commandHandler holds a reference to gamingTable -
 * initiates gamingTable
 */

public class Game {

	private int numOfHumanPlayers;
	private int numOfAutoPlayers;
	private int numOfConnectedPlayers;
	private List<PlayerControl> players;

	private CommandHandler commandHandler;
	private GamingTable gamingTable;

	private Server2ClientsCommunication server2ClientsCommunication;
	
	public GamingTable getGamingTable() {
		return gamingTable;
	}

	/**
	 * 
	 */
	public Game() {
		gamingTable = new GamingTable();
		commandHandler = new CommandHandler(this);
	}

	/**
	 * @param numOfHumanPlayers
	 * @param numOfAutoPlayers
	 * @param server2ClientsCommunication 
	 */
	public Game(int numOfPlayers, int numOfAutoPlayers, Server2ClientsCommunication server2ClientsCommunication) {
		super();
		this.numOfHumanPlayers = numOfPlayers;
		this.numOfAutoPlayers = numOfAutoPlayers;
		this.players = new ArrayList<PlayerControl>();
		this.gamingTable = new GamingTable();
		this.commandHandler = new CommandHandler(this);
		this.server2ClientsCommunication = server2ClientsCommunication;
	}

	public boolean isGameFull() {
		return (numOfConnectedPlayers == (numOfHumanPlayers + numOfAutoPlayers));
	}


	public boolean addPlayer(PlayerControl player) {
		if (!isGameFull() ) 
		{
			players.add(player);
			gamingTable.addPlayer(player.getPlayer());
			numOfConnectedPlayers++;
			return true;
		}
		return false;
	}

	public CommandHandler getCommandHandler() {
		return commandHandler;
	}

	public PlayerControl getPlayerControl(Player currentDefender) {
		for (PlayerControl playerControl : players) {
			if (playerControl.getPlayer() == currentDefender)
				return playerControl;
		}
		return null;
	}

	public List<PlayerControl> getPlayers() {
		return players;
	}

	public boolean allPlayersReady() {
		for (PlayerControl player : players) {
			if(player.isInitialized() == false)
				return false;
		}
		return true;	
	}

	/**
	 * @return the server2ClientsCommunication
	 */
	public Server2ClientsCommunication getServer2ClientsCommunication() {
		return server2ClientsCommunication;
	}
}
